<template>
  <div class="document-versions-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <div class="page-info">
          <h1>版本历史</h1>
          <p>{{ document.title }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="goToDocument">查看当前版本</el-button>
      </div>
    </div>

    <div class="versions-content">
      <div class="versions-list">
        <div 
          v-for="(version, index) in versions"
          :key="version.id"
          class="version-item"
          :class="{ 'current': version.isCurrent }"
        >
          <div class="version-info">
            <div class="version-header">
              <div class="version-meta">
                <span class="version-number">版本 {{ versions.length - index }}</span>
                <el-tag v-if="version.isCurrent" type="success" size="small">当前版本</el-tag>
                <span class="version-time">{{ formatTime(version.createTime) }}</span>
              </div>
              <div class="version-actions">
                <el-button size="small" @click="viewVersion(version)">查看</el-button>
                <el-button 
                  v-if="!version.isCurrent" 
                  size="small" 
                  type="primary" 
                  @click="restoreVersion(version)"
                >
                  恢复此版本
                </el-button>
                <el-button 
                  size="small" 
                  @click="compareVersion(version)"
                >
                  对比
                </el-button>
              </div>
            </div>
            
            <div class="version-details">
              <div class="author-info">
                <el-avatar :src="version.authorAvatar" :size="32" />
                <div class="author-meta">
                  <div class="author-name">{{ version.authorName }}</div>
                  <div class="commit-message">{{ version.description || '版本更新' }}</div>
                </div>
              </div>
              
              <div class="version-stats">
                <div class="stat-item">
                  <span class="label">字数：</span>
                  <span class="value">{{ version.wordCount || 0 }}</span>
                </div>
                <div class="stat-item">
                  <span class="label">变更：</span>
                  <span class="changes">
                    <span class="additions" v-if="version.additions > 0">+{{ version.additions }}</span>
                    <span class="deletions" v-if="version.deletions > 0">-{{ version.deletions }}</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <div class="version-preview" v-if="expandedVersion === version.id">
            <div class="preview-content">
              <div class="content-preview" v-html="getPreviewContent(version)"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 版本对比 -->
      <div class="version-compare" v-if="compareVersions.length === 2">
        <el-card>
          <template #header>
            <div class="compare-header">
              <span>版本对比</span>
              <el-button size="small" @click="clearCompare">清除对比</el-button>
            </div>
          </template>
          <div class="compare-content">
            <div class="compare-side">
              <h4>版本 {{ getVersionNumber(compareVersions[0]) }}</h4>
              <div class="compare-meta">
                {{ compareVersions[0].authorName }} · {{ formatTime(compareVersions[0].createTime) }}
              </div>
              <div class="compare-text" v-html="compareVersions[0].content"></div>
            </div>
            <div class="compare-divider"></div>
            <div class="compare-side">
              <h4>版本 {{ getVersionNumber(compareVersions[1]) }}</h4>
              <div class="compare-meta">
                {{ compareVersions[1].authorName }} · {{ formatTime(compareVersions[1].createTime) }}
              </div>
              <div class="compare-text" v-html="compareVersions[1].content"></div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getDocumentDetail,
  getDocumentVersions,
  restoreDocumentVersion
} from '@/api/document'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const document = ref({})
const versions = ref([])
const expandedVersion = ref(null)
const compareVersions = ref([])

// 页面加载
onMounted(async () => {
  await loadDocument()
  await loadVersions()
})

// 加载文档信息
const loadDocument = async () => {
  try {
    const response = await getDocumentDetail(route.params.id)
    if (response.code === 200) {
      document.value = response.data
    }
  } catch (error) {
    console.error('获取文档信息失败:', error)
    ElMessage.error('获取文档信息失败')
  }
}

// 加载版本历史
const loadVersions = async () => {
  try {
    const response = await getDocumentVersions(route.params.id)
    if (response.code === 200) {
      versions.value = response.data || []
      // 标记当前版本
      if (versions.value.length > 0) {
        versions.value[0].isCurrent = true
      }
    }
  } catch (error) {
    console.error('获取版本历史失败:', error)
    ElMessage.error('获取版本历史失败')
  }
}

// 查看版本
const viewVersion = (version) => {
  if (expandedVersion.value === version.id) {
    expandedVersion.value = null
  } else {
    expandedVersion.value = version.id
  }
}

// 恢复版本
const restoreVersion = async (version) => {
  try {
    await ElMessageBox.confirm(
      `确认要恢复到版本 ${getVersionNumber(version)} 吗？这将创建一个新的版本。`,
      '确认恢复版本',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await restoreDocumentVersion(document.value.id, version.id)
    ElMessage.success('版本恢复成功')
    loadVersions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复版本失败:', error)
      ElMessage.error('恢复版本失败')
    }
  }
}

// 对比版本
const compareVersion = (version) => {
  if (compareVersions.value.length === 2) {
    compareVersions.value = [version]
  } else if (compareVersions.value.includes(version)) {
    compareVersions.value = compareVersions.value.filter(v => v.id !== version.id)
  } else {
    compareVersions.value.push(version)
  }
}

// 清除对比
const clearCompare = () => {
  compareVersions.value = []
}

// 获取版本号
const getVersionNumber = (version) => {
  const index = versions.value.findIndex(v => v.id === version.id)
  return versions.value.length - index
}

// 获取预览内容
const getPreviewContent = (version) => {
  if (!version.content) return ''
  // 简化的 markdown 渲染，实际应该使用专门的 markdown 解析器
  return version.content.substring(0, 500) + (version.content.length > 500 ? '...' : '')
}

// 跳转到文档
const goToDocument = () => {
  router.push(`/document/${document.value.id}`)
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.document-versions-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    .page-info {
      h1 {
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 4px 0;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.versions-content {
  max-width: 1000px;
  margin: 0 auto;
}

.versions-list {
  .version-item {
    background: white;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    overflow: hidden;
    
    &.current {
      border-left: 4px solid #409eff;
    }
    
    .version-info {
      padding: 20px;
      
      .version-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        
        .version-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .version-number {
            font-weight: 600;
            color: #303133;
          }
          
          .version-time {
            color: #909399;
            font-size: 14px;
          }
        }
        
        .version-actions {
          display: flex;
          gap: 8px;
        }
      }
      
      .version-details {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .author-info {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .author-meta {
            .author-name {
              font-weight: 500;
              color: #303133;
              margin-bottom: 4px;
            }
            
            .commit-message {
              color: #606266;
              font-size: 14px;
            }
          }
        }
        
        .version-stats {
          display: flex;
          gap: 20px;
          
          .stat-item {
            display: flex;
            align-items: center;
            gap: 4px;
            
            .label {
              color: #909399;
              font-size: 14px;
            }
            
            .value {
              color: #303133;
              font-weight: 500;
            }
            
            .changes {
              display: flex;
              gap: 8px;
              
              .additions {
                color: #67c23a;
              }
              
              .deletions {
                color: #f56c6c;
              }
            }
          }
        }
      }
    }
    
    .version-preview {
      border-top: 1px solid #f0f0f0;
      padding: 20px;
      background-color: #fafafa;
      
      .content-preview {
        max-height: 300px;
        overflow-y: auto;
        line-height: 1.6;
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.version-compare {
  margin-top: 30px;
  
  .compare-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .compare-content {
    display: flex;
    gap: 20px;
    
    .compare-side {
      flex: 1;
      
      h4 {
        margin: 0 0 8px 0;
        color: #303133;
      }
      
      .compare-meta {
        color: #909399;
        font-size: 12px;
        margin-bottom: 16px;
      }
      
      .compare-text {
        max-height: 400px;
        overflow-y: auto;
        line-height: 1.6;
        color: #606266;
        font-size: 14px;
        padding: 16px;
        background-color: #fafafa;
        border-radius: 4px;
      }
    }
    
    .compare-divider {
      width: 1px;
      background-color: #e4e7ed;
    }
  }
}

@media (max-width: 768px) {
  .document-versions-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    padding: 20px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .version-item {
    .version-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }
    
    .version-details {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
    }
  }
  
  .compare-content {
    flex-direction: column;
    
    .compare-divider {
      width: 100%;
      height: 1px;
    }
  }
}
</style>
